import 'package:chat/common/model/Friend.dart';
import 'package:chat/common/model/User.dart';
import 'package:chat/common/service/HttpService.dart';
import 'package:chat/common/utils/storage.dart' show Storage;
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:pinyin/pinyin.dart';

class FriendController extends GetxController {
  FriendController();

  var groupedFriends = <String, List<Friend>>{}.obs;

  void setFriends(Map<String, dynamic> data) {
    Map<String, List<Friend>> temp = {};

    data.forEach((key, value) {
      final List<Friend> friends = (value as List).map((e) => Friend.fromJson(e)).toList();
      temp[key] = friends;
    });

    // 排序：字母 A-Z, # 放最后
    var sortedKeys =
        temp.keys.toList()..sort((a, b) {
          if (a == '#') return 1;
          if (b == '#') return -1;
          return a.compareTo(b);
        });

    Map<String, List<Friend>> sortedMap = {};
    for (var key in sortedKeys) {
      var list = temp[key]!;
      list.sort((a, b) => a.notes.toLowerCase().compareTo(b.notes.toLowerCase()));
      sortedMap[key] = list;
    }

    groupedFriends.value = sortedMap;
  }

  Future<void> fetchData() async {
    try {
      UserModel? user = await Storage().getUser();
      final response = await HttpService.to.get("/friend/list", query: {"userId": user?.uid});

      if (response.statusCode == 200 && response.data["code"] == 200) {
        print("✅ 接口返回数据：${response.data}");

        // data 是一个 Map<String, dynamic>
        final Map<String, dynamic> data = response.data["data"] ?? {};

        setFriends(data);
      }
    } catch (e) {
      print("❌ 获取好友列表失败: $e");
    }
  }

  _initData() {
    update(["friend"]);
  }

  void onTap() {}

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  @override
  void onInit() {
    super.onInit();
    fetchData();
  }
}
